﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media.Media3D;
using System.Windows.Media;
using System.Windows.Controls;
using System.Runtime.InteropServices;
using System.Threading;
using System.Linq.Expressions;
using System.Windows.Threading;
using System.IO;

namespace System
{
    public static class Extensions
    {
        /// <summary>
        /// ExecuteExternal specified action on thread GUI items were created on
        /// </summary>
        /// <param name="action">Action to be executed</param>
        /// <param name="sender">Invoker object</param>
        /// <param name="args">Arguments to be passed</param>
        public static void Invoke<T>(this DependencyObject uiElement, EventHandler<T> action, object sender, T args) where T : EventArgs
        {
            uiElement.Invoke(action, sender, args);
        }

        /// <summary>
        /// ExecuteExternal specified action on thread GUI items were created on
        /// </summary>
        /// <param name="action">Action to be executed</param>
        /// <param name="sender">Invoker object</param>
        /// <param name="args">Arguments to be passed</param>
        public static void Invoke(this DependencyObject uiElement, EventHandler action, object sender, EventArgs args)
        {
            uiElement.Invoke(action, sender, args);
        }

        /// <summary>
        /// ExecuteExternal specified action on thread GUI items were created on
        /// </summary>
        /// <param name="action">Action to be executed</param>
        /// <param name="arguments">Arguments to be passed</param>
        public static void Invoke(this DependencyObject uiElement, Delegate action, params object[] arguments)
        {
            if (uiElement.Dispatcher.Thread == Thread.CurrentThread)
            {
                action.DynamicInvoke(arguments);
            }
            else
            {
                uiElement.Dispatcher.Invoke(action, DispatcherPriority.Normal, arguments);
            }
        }

        /// <summary>
        /// ExecuteExternal specified action on thread GUI items were created on
        /// </summary>
        /// <param name="action">Action to be executed</param>
        /// <returns>Result of execution</returns>
        public static T Invoke<T>(this DependencyObject uiElement, Func<T> action)
        {
            T retval = default(T);
            uiElement.Invoke(() => { retval = action(); });

            return retval;
        }

        /// <summary>
        /// ExecuteExternal specified action on thread GUI items were created on
        /// </summary>
        /// <param name="action">Action to be executed</param>
        public static void Invoke(this DependencyObject uiElement, Action action)
        {
            if (uiElement.Dispatcher.Thread == Thread.CurrentThread)
            {
                action();
            }
            else
            {
                uiElement.Dispatcher.Invoke(action);
            }
        }


        public static Q Invoke<T, Q>(this T uiElement, Func<T, Q> action) where T : DependencyObject
        {
            return uiElement.Invoke(() => action(uiElement));
        }

        public static void Invoke<T>(this T uiElement, Action<T> action) where T : DependencyObject
        {
            uiElement.Invoke(() => action(uiElement));
        }

        public static void Invoke(this DependencyObject uiElement, LambdaExpression action)
        {
            uiElement.Invoke(action.Compile());
        }

        public static T GetValue<UI, T>(this UI uiElement, Func<UI, T> action) where UI : DependencyObject
        {
            if (uiElement.Dispatcher.Thread == Thread.CurrentThread)
            {
                return action(uiElement);
            }
            else
            {
                return uiElement.Invoke(() => action(uiElement));
            }
        }

        public static T GetDependencyValue<T>(this DependencyObject uiElement, DependencyProperty prop)
        {
            return uiElement.GetValue(t => (T)t.GetValue(prop));
        }

        public static void SetDependencyValue(this DependencyObject uiElement, DependencyProperty prop, object value)
        {
            if (uiElement.Dispatcher.Thread == Thread.CurrentThread)
            {
                uiElement.SetValue(prop, value);
            }
            else
            {
                uiElement.Invoke(() => { uiElement.SetValue(prop, value); });
            }
        }

        public static byte[] ToByteArray(this object obj)
        {
            if (obj == null)
            {
                return new byte[0];
            }

            var size = Marshal.SizeOf(obj);

            if (size <= 0)
            {
                return new byte[0];
            }

            var buff = new byte[size];

            var handle = GCHandle.Alloc(buff, GCHandleType.Pinned);

            try
            {
                Marshal.StructureToPtr(obj, handle.AddrOfPinnedObject(), false);
            }
            finally
            {
                handle.Free();
            }

            return buff;
        }

        public static T ConvertTo<T>(this byte[] buff)
        {
            if (buff == null)
            {
                if (typeof(T).IsValueType)
                {
                    throw new ArgumentNullException();
                }

                return default(T);
            }

            var handle = GCHandle.Alloc(buff, GCHandleType.Pinned);
            try
            {
                var ptr = handle.AddrOfPinnedObject();

                return (T)Marshal.PtrToStructure(ptr, typeof(T));
            }
            finally
            {
                handle.Free();
            }

            throw new InvalidOperationException();
        }

        public static TObject Read<TObject>(this Stream stream)
        {
            var buff = new byte[Marshal.SizeOf(typeof(TObject))];

            if (stream.Read(buff) != buff.Length)
            {
                return default(TObject);
            }

            return buff.ConvertTo<TObject>();
        }

        public static void Write<TObject>(this Stream stream, TObject obj)
        {
            if (!typeof(TObject).IsValueType)
            {
                if (object.ReferenceEquals(null, obj))
                {
                    return;
                }
            }

            var buff = obj.ToByteArray();

            stream.Write(buff);
        }

        public static int Read(this Stream stream, byte[] buff)
        {
            if (buff == null || buff.Length == 0)
            {
                return 0;
            }

            return stream.Read(buff, 0, buff.Length);
        }

        public static void Write(this Stream stream, byte[] buff)
        {
            if (buff != null && buff.Length != 0)
            {
                stream.Write(buff, 0, buff.Length);
            }
        }

        public static DependencyObject FindAnchestor(this DependencyObject current, params Type[] types)
        {
            if (types.Length == 0)
            {
                throw new ArgumentException();
            }

            while (current != null && (current is Visual || current is Visual3D || current is UIElement))
            {
                if (types.Any(t => t == current.GetType() || t.IsAssignableFrom(current.GetType())))
                {
                    return current;
                }

                current = VisualTreeHelper.GetParent(current);
            }

            return null;
        }

        public static T FindAnchestor<T>(this DependencyObject current) where T : DependencyObject
        {
            //while (current != null && (current is Visual || current is Visual3D || current is UIElement))
            //{
            //    if (current is T)
            //    {
            //        return (T)(object)current;
            //    }

            //    current = VisualTreeHelper.GetParent(current);
            //}

            //return null;

            return (T)current.FindAnchestor(typeof(T));
        }

        public static IEnumerable<DependencyObject> GetChildren(this DependencyObject current)
        {
            if (current != null && (current is Visual || current is Visual3D))
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(current); i++)
                {
                    yield return VisualTreeHelper.GetChild(current, i);
                }
            }

            yield break;
        }

        public static T FindSibling<T>(this DependencyObject current, string name) where T : FrameworkElement
        {
            if (current != null && (current is Visual || current is Visual3D))
            {
                var obj = VisualTreeHelper.GetParent(current);

                return obj.GetChildren().Where(t => t != current && t is T && (t as T).Name == name).Cast<T>().FirstOrDefault();
            }

            return null;
        }

        public static T FindDescendant<T>(this DependencyObject current, string name) where T : FrameworkElement
        {
            if (current != null && (current is Visual || current is Visual3D))
            {
                if (current is T)
                {
                    if (string.IsNullOrWhiteSpace(name) || (current as FrameworkElement).Name == name)
                    {
                        return (T)(object)current;
                    }
                }

                var items = new Queue<DependencyObject>();
                items.Enqueue(current);

                do
                {
                    current = items.Dequeue();

                    foreach (var c in current.GetChildren())
                    {
                        if (c is T)
                        {
                            if (!string.IsNullOrWhiteSpace(name))
                            {
                                if ((c as FrameworkElement).Name == name)
                                {
                                    return (T)(object)c;
                                }
                            }
                            else
                            {
                                return (T)(object)c;
                            }
                        }

                        if (VisualTreeHelper.GetChildrenCount(c) > 0)
                        {
                            items.Enqueue(c);
                        }
                    }
                } while (items.Count > 0);
            }
            return null;
        }

        public static T FindDescendant<T>(this DependencyObject current) where T : FrameworkElement
        {
            return current.FindDescendant<T>(null);
        }

    }
}
